package com.wangxinyuchuan.algorithm.phase1;

import java.util.Arrays;

/**
 * @author wangxinyuchuan
 * @version _4_冒泡排序.java v1.0 2023/5/25 9:37 PM wangxinyuchuan Exp $
 */
public class _4_冒泡排序 {
    public static void main(String[] args) {
        int[] array = {1, 4, 7, 3, 2, 5, 8, 6};
        System.out.println(Arrays.toString(bubbleSort(array)));
    }

    /**
     * 冒泡排序
     * 数组下标从0开始比较array[i]和array[i+1]的值然后交换，确定末尾最大值，i++
     * 如此循环
     * @param array
     * @return
     */
    public static int[] bubbleSort(int[] array) {
        if (array == null || array.length < 2) {
            return array;
        }
        int length = array.length;
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length-1-i; j++) {
                if (array[j] > array[j+1]) {
                    swap(array, j, j+1);
                }
            }
        }
        return array;
    }

    private static void swap(int[] array, int i, int minIndex) {
        int temp = array[i];
        array[i] = array[minIndex];
        array[minIndex] = temp;
    }
}
